const Koa = require("koa");
const app = new Koa();
const views = require("koa-views");
const json = require("koa-json");
const onerror = require("koa-onerror");
const bodyparser = require("koa-bodyparser");
const logger = require("koa-logger");
const session = require("koa-generic-session");
const redisStore = require("koa-redis");
const koaStatic = require("koa-static");
const path = require("path");
// const jwtKoa = require('koa-jwt') 

const { REDIS_CONF } = require("./conf/db");
const blogAPIRouter = require('./routes/api/blogHome')
const blogViewRouter = require('./routes/view/blog')
const userViewRouter = require("./routes/view/user");
const userAPIRouter = require("./routes/api/user");
const utilsAPIRouter = require("./routes/api/utils")
const error = require("./routes/view/error");
const { JWT_SECERT, SESSION_SECERT } = require("./conf/constants");

// error handler
let onerrorConf = {};
if (process.env.prod) {
  onerrorConf = {
    redirect: "/error",
  };
}
onerror(app, onerrorConf);

//jwt验证
// app.use(jwtKoa({
//     secret: JWT_SECERT,
// }).unless({
//     path: [/^\/users\/login/]
// }))

// middlewares
app.use(
  bodyparser({
    enableTypes: ["json", "form", "text"],
  })
);
app.use(json());
app.use(logger());
app.use(koaStatic(path.join(__dirname, "/public")));
app.use(koaStatic(path.join(__dirname, "..", "/uploadFiles")));

app.use(
  views(__dirname + "/views", {
    extension: "ejs",
  })
);

// session 配置
app.keys = [SESSION_SECERT];
app.use(
  session({
    key: "weibo.sid", //cookie key
    prefix: "weibo:sess:", //redis key的前缀
    cookie: {
      path: "/",
      httpOnly: true,
      maxAge: 24 * 60 * 60 * 1000,
    },
    store: redisStore({
      ...REDIS_CONF,
      db: 1,
    }),
  })
);

// logger
// app.use(async (ctx, next) => {
//   const start = new Date()
//   await next()
//   const ms = new Date() - start
//   console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
// })

// routes
app.use(blogAPIRouter.routes(), blogAPIRouter.allowedMethods());
app.use(blogViewRouter.routes(), blogViewRouter.allowedMethods());
app.use(utilsAPIRouter.routes(), utilsAPIRouter.allowedMethods())
app.use(userViewRouter.routes(), userViewRouter.allowedMethods());
app.use(userAPIRouter.routes(), userAPIRouter.allowedMethods());
app.use(error.routes(), error.allowedMethods()); //404最后注册

// error-handling
app.on("error", (err, ctx) => {
  console.error(err);
});

module.exports = app;
